package org.jeecg.modules.tz.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.RestUtil;
import org.jeecg.modules.tz.entity.TzNetwork;
import org.jeecg.modules.tz.entity.TzNetworkItem;
import org.jeecg.modules.tz.mapper.TzNetworkMapper;
import org.jeecg.modules.tz.service.ITzNetworkItemService;
import org.jeecg.modules.tz.service.ITzNetworkService;
import org.jeecg.modules.tz.service.ITzThirdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: tz_network
 * @Author: jeecg-boot
 * @Date:   2024-08-26
 * @Version: V1.0
 */
@Service
public class TzThirdServiceImpl  implements ITzThirdService {
    @Value("${third.notifyUrl}")
    public String notifyUrl;//推送告警日志地址

    @Value("${third.machinePortList}")
    public String machinePortList;//获取代理配置地址

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ITzNetworkService tzNetworkService;
    @Autowired
    private ITzNetworkItemService tzNetworkItemService;

    @Override
    public boolean machinePortList() {
        HttpHeaders headers = this.getHeaders();
        // 请求方式是 GET 代表获取数据
        HttpMethod method = HttpMethod.POST;
        // 利用 RestUtil 请求该url
        ResponseEntity<JSONObject> result = RestUtil.request(machinePortList, method, headers, null, null, JSONObject.class);
        if (result != null && result.getBody() != null) {
            System.out.println("返回结果1：" + result.getBody().toJSONString());
            JSONArray result1 = result.getBody().getJSONArray("result");
            for(int i = 0;i<result1.size();i++){
                JSONObject jsonObject = result1.getJSONObject(i);
                String name = jsonObject.getString("name");
                String jpomUrl = jsonObject.getString("jpomUrl");//主机IP
                //192.168.136.10:2123
                String[] split = jpomUrl.split(":");
                String ip = split[0];//主机IP
                //如果主机存在，则更新，不存在，则新增
                LambdaQueryWrapper<TzNetwork> tzNetWork = new LambdaQueryWrapper<>();
                tzNetWork.eq(TzNetwork::getTzIp,ip);
                long count = tzNetworkService.count(tzNetWork);
                TzNetwork tn = new TzNetwork();
                if(count<=0){
                    tn.setTzName(name);
                    tn.setTzIp(ip);
                    tn.setStatus(0);
                    tn.setMyPort("8888");
                    tn.setServIp(ip);
                    tn.setServPort("9999");
                    tn.setFreq("10");
                    tn.setDescription(name);
                    tzNetworkService.save(tn);
                }else{
                    tn = tzNetworkService.getOne(tzNetWork);
                }


                String id = jsonObject.getString("id");
                JSONObject ports = jsonObject.getJSONObject("ports");
                if(ports != null){
                    if(count<=0){
                        for (String key : ports.keySet()) {
                            JSONArray jsonArray = ports.getJSONArray(key);
                            for(int j = 0;j<jsonArray.size();j++){
                                String acrossIp = jsonArray.getString(j);//ip
                                TzNetworkItem tni = new TzNetworkItem();
                                tni.setNetworkId(tn.getId());
                                tni.setLocalIp(ip);
                                tni.setLocalPort(key);
                                tni.setLocalProto("tcp");
                                tni.setAcrossIp(acrossIp);
                                tni.setAcrossPort("2001");
                                tzNetworkItemService.save(tni);
                            }
                        }
                    }else{
                        LambdaQueryWrapper<TzNetworkItem> query = new LambdaQueryWrapper<>();
                        query.eq(TzNetworkItem::getNetworkId,tn.getId());
                        tzNetworkItemService.remove(query);//先删除，再添加
                        for (String key : ports.keySet()) {
                            JSONArray jsonArray = ports.getJSONArray(key);
                            for(int j = 0;j<jsonArray.size();j++){
                                String acrossIp = jsonArray.getString(j);//ip
                                TzNetworkItem tni = new TzNetworkItem();
                                tni.setNetworkId(tn.getId());
                                tni.setLocalIp(ip);
                                tni.setLocalPort(key);
                                tni.setLocalProto("tcp");
                                tni.setAcrossIp(acrossIp);
                                tni.setAcrossPort("2001");
                                tzNetworkItemService.save(tni);
                            }
                        }
                    }
                }

            }
            System.out.println("返回结果2：" + result1.toJSONString());
            return true;
        } else {
            System.out.println("查询失败");
        }
        return false;
    }

    @Override
    public void notifyLog(String title, String content) {
        HttpHeaders headers = this.getHeaders();
        // 请求方式是 GET 代表获取数据
        HttpMethod method = HttpMethod.POST;
        JSONObject params = new JSONObject();
        params.put("title", title);
        params.put("content", content);
        // 利用 RestUtil 请求该url
        ResponseEntity<JSONObject> result = RestUtil.request(notifyUrl, method, headers, null, params, JSONObject.class);
    }

    private HttpHeaders getHeaders() {
        String token = this.getToken();
        System.out.println("请求Token：" + token);

        HttpHeaders headers = new HttpHeaders();
        String mediaType = MediaType.APPLICATION_JSON_VALUE;
        headers.setContentType(MediaType.parseMediaType(mediaType));
        headers.set("Accept", mediaType);
        headers.set("X-Access-Token", token);
        return headers;
    }

    private String getToken() {
        String token = JwtUtil.sign("admin", "123456");
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, 60);
        return token;
    }
}
